import { message } from "@/utils/message";
import {
  queryBannerList,
  updateBannerStatus,
  deleteBanner
} from "@/api/sysbanner";
import { ElMessageBox } from "element-plus";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, computed, onMounted } from "vue";

export function useBanner() {
  const INITIAL_DATA = {
    id: "",
    uid: "",
    type: "",
    title: "",
    logo: "",
    des: "",
    content: "",
    zt: "0",
    noticetime: "",
    orderby: "0",
    addtime: "",
    updatetime: ""
  };

  const searchForm = reactive({
    uid: "",
    title: "",
    zt: "1"
  });
  const dialogVisible = ref(false);
  const formData = ref({ ...INITIAL_DATA });

  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "编号",
      prop: "id",
      minWidth: 130
    },
    {
      label: "类型",
      prop: "type",
      minWidth: 130,
      formatter: row => {
        switch (row.type) {
          case 1:
            return "图文";
          case 2:
            return "视频";
        }
      }
    },
    {
      label: "公告名称",
      prop: "title",
      minWidth: 130
    },
    {
      label: "状态",
      prop: "zt",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.zt}
          active-value={1}
          inactive-value={0}
          active-text="已发布"
          inactive-text="待发布"
          inline-prompt
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "发布时间",
      minWidth: 90,
      prop: "noticetime"
    },
    {
      label: "排序",
      prop: "orderby",
      minWidth: 60
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.zt === 1 ? "关闭" : "开启"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.title
      }</strong>公告吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        updateBannerStatus({
          id: row.id,
          zt: row.zt
        })
          .then(res => {
            if (res.success) {
              message("已成功修改公告状态", { type: "success" });
              switchLoadMap.value[index] = Object.assign(
                {},
                switchLoadMap.value[index],
                {
                  loading: false
                }
              );
            } else {
              row.zt === 0 ? (row.zt = 1) : (row.zt = 0); //异常状态恢复
              message("修改状态异常:" + res.errMsg, { type: "error" });
            }
          })
          .catch(error => {
            row.zt === 0 ? (row.zt = 1) : (row.zt = 0); //异常状态恢复
            message("修改状态异常:" + JSON.stringify(error), { type: "error" });
          });
      })
      .catch(() => {
        row.zt === 0 ? (row.zt = 1) : (row.zt = 0); //状态恢复
      });
  }

  function handleAdd() {
    dialogVisible.value = true;
    formData.value = { ...INITIAL_DATA };
  }

  function handleUpdate(row) {
    dialogVisible.value = true;
    formData.value = {
      ...row,
      type: row.type == 1 ? "1" : "2",
      zt: row.zt == 0 ? "0" : "1"
    };
  }

  function handleDelete(row) {
    deleteBanner(row)
      .then(res => {
        if (res.success) {
          message("删除成功", { type: "success" });
          onSearch();
        } else {
          message("删除数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("删除数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    queryBannerList({
      uid: searchForm.uid,
      title: searchForm.title,
      zt: searchForm.zt,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    })
      .then(res => {
        if (res.success) {
          dataList.value = res.data.list;
          pagination.total = res.data.total;
          loading.value = false;
        } else {
          message("查询数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("查询数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    dialogVisible,
    formData,
    searchForm,
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    handleAdd,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
